//
//  AppDelegate.m
//  PartyClassCloud
//
//  Created by 九酷 on 2018/8/13.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "AppDelegate.h"
#import "BaiduMobStat.h"
#import <BMKLocationkit/BMKLocationComponent.h>

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
 

#define JPUSHIAPPKey "dbdf8c2d22f549ce8b58f857"

@interface AppDelegate ()<JPUSHRegisterDelegate,BMKLocationAuthDelegate>

@end

@implementation AppDelegate

//此方法会在设备横竖屏变化的时候调用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (self.rotateDirection == 1){
        return UIInterfaceOrientationMaskLandscapeRight; // 支持右屏旋转
    }
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for(UIWindow *window in windows) {
        if(window.rootViewController == nil){
            UIViewController* vc = [[UIViewController alloc]initWithNibName:nil bundle:nil];
            window.rootViewController = vc;
        }
    }
    // 文件路径
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *result = NullStringjudgment([defaults objectForKey:@"token"]); //dict[@"token"];
//    NSLog(@"%@>>>token",result);
    if(result.length == 0){
        LSZPasswordLoginVC * vc = [[LSZPasswordLoginVC alloc]init];
        [self.window setRootViewController:vc];
    }else{
        [InterfaceJumpEncapsulation jumpToNewTabBar:0];
    }
    [[UINavigationBar appearance]setBarTintColor:themeColor];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
//    在appDelegate中通知app支持后台播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    [LSZRequestData detectionVersionUpdate:^(BOOL isOK, NSString * str, NSDictionary * dic) {
        if(isOK == YES){
           NSInteger versionNumber = [dic[@"versionNumber"] integerValue];
            NSLog(@"%d>>>>",currentVersionNumber);
            if (versionNumber > currentVersionNumber) {
//需要版本更新
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:dic[@"summary"]   preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                    //id后的需要换成这个APP的
                    NSString * url = [[NSString alloc]initWithFormat:@"http://itunes.apple.com/app/id%@",@"1445711010"];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                }];
                //先设置不强更
                if ([dic[@"force"] integerValue] == 1) {
                }else{
                    //不强更
                    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                        NSLog(@"取消");
                    }];
                    [alert addAction:cancelAction];
                }
                [alert addAction:okAction];
                [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
            }
        }
    }];
    [[BaiduMobStat defaultStat] startWithAppId:@"d111088257"];
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:@"eiLH9TQn5SrHjX6tbvFDu78dVHfas8HV" authDelegate:self];

    [self addJPUSH:launchOptions];//极光
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    
    return YES;
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *contentString = [userInfo valueForKey:@"content"];
    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:contentString preferredStyle:UIAlertControllerStyleAlert];
//
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"确定");
//    }];
//    [alertController addAction:cancelAction];
//    [alertController addAction:okAction];
//    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    UNMutableNotificationContent * contentM = [[UNMutableNotificationContent alloc]init];
//    contentM.title = @"新郑扶贫";//小标题
//    contentM.subtitle = @"小标题";//二标题
    NSDictionary * dicJson = [self dictionaryWithJsonString:contentString];
    contentM.body = [NSString localizedUserNotificationStringForKey:[NSString stringWithFormat:@"%@", dicJson[@"content"]] arguments:nil];
 
    contentM.sound = [UNNotificationSound defaultSound];
    contentM.badge = @0;
    contentM.categoryIdentifier = @"catorgry";
    contentM.launchImageName = @"banner";
 
//    NSString * path4 = [[NSBundle mainBundle] pathForResource:@"banner" ofType:@"png"];
//    NSString * path3 = [[NSBundle mainBundle] pathForResource:@"nfg_bg" ofType:@"png"];
//    NSError * error;
//    UNNotificationAttachment * att;
//    if (@available(iOS 10.0, *)) {
//        att = [UNNotificationAttachment attachmentWithIdentifier:@"hah" URL:[NSURL fileURLWithPath:path4] options:nil error:&error];
//    } else {
//        // Fallback on earlier versions
//    }
//    UNNotificationAttachment * att3;
//    if (@available(iOS 10.0, *)) {
//         att3 = [UNNotificationAttachment attachmentWithIdentifier:@"hah" URL:[NSURL fileURLWithPath:path3] options:nil error:&error];
//    } else {
//        // Fallback on earlier versions
//    }
//    content.pathComponents == [NSArray arrayWithObjects:att,att3, nil];
    //添加触发器
    UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];
    UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"TimeSecond" content:contentM trigger:trigger];
    UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"1111111");
    }];
}
#pragma mark - 极光推送
-(void)addJPUSH:(NSDictionary *)launchOptions
{
    //添加初始化APNs代码
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //添加初始化JPush代码
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@JPUSHIAPPKey
                          channel:@"App Store"
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@>>>>>",deviceToken);
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    //    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //        [JPUSHService handleRemoteNotification:userInfo];
    //    }
    //    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    //    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString * body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;// 推送消息的标题
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        [JPUSHService handleRemoteNotification:userInfo];
//        NSLog(@"iOS10 前台收到远程通知:%@",[self logDic:userInfo]);
        [self recordTheInformationSentByTheNotification:userInfo];
    }
    else{
        // 判断为本地通知 badge：%@，\n
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,sound,userInfo);
        [self newRecordTheInformationSentByTheNotification:title :body];
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    //    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //        [JPUSHService handleRemoteNotification:userInfo];
    //    }
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    //    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title =content.title;// 推送消息的标题
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
//        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        [self recordTheInformationSentByTheNotification:userInfo];
    }
    else{
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,sound,userInfo);
        //走的这个
        [self newRecordTheInformationSentByTheNotification:title :body];
    }
    completionHandler();  // 系统要求执行这个方法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark - 记录通知传过来的信息
-(void)recordTheInformationSentByTheNotification:(NSDictionary *)userInfo
{
    [JPUSHService setBadge:0];
//    NSDictionary * userInfo = [notification userInfo];
    NSString *contentStr = userInfo[@"aps"][@"alert"];
    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:contentStr preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self alertViewClickbuttonIndex];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
}
#pragma mark - 走本地的通知
-(void)newRecordTheInformationSentByTheNotification:(NSString *)string :(NSString *)str
{
    [JPUSHService setBadge:0];
    //    NSDictionary * userInfo = [notification userInfo];
//    NSString *content = userInfo[@"aps"][@"alert"];
//    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
    if ([NullStringjudgment(NSStr(string)) isEqualToString:@""]) {
        string = @"温馨提示";
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:str preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self alertViewClickbuttonIndex];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
#pragma mark - 跳转通知界面
-(void)alertViewClickbuttonIndex
{
    __weak typeof(self) weakSelf = self;
    // 类名
    NSString *class = @"LSZNoticeParentViewController";
    const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
    // 从一个字串返回一个类
    Class newClass = objc_getClass(className);
    if (!newClass){
        // 创建一个类
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        // 注册你创建的这个类
        objc_registerClassPair(newClass);
    }
    // 创建对象
    id instance = [[newClass alloc] init];
    if ([instance isKindOfClass:[LSZNoticeParentViewController class]]) {
        UITabBarController *tabVC = (UITabBarController *)weakSelf.window.rootViewController;
        UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
        // 跳转到对应的控制器
        [pushClassStance pushViewController:instance animated:YES];
    }else{
        UITabBarController *tabVC = (UITabBarController *)weakSelf.window.rootViewController;
        UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
        // 跳转到对应的控制器
        [pushClassStance pushViewController:instance animated:YES];
    }
}
- (void)applicationWillResignActive:(UIApplication *)application{
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
